<?php
/**
 * Smart Library - Smart Framework
 * http://smart-framework.highet.eu
 *
 * @category   SmartL
 * @package    SmartL_Zend
 * @subpackage Translate
 * @copyright  Copyright (c) 2005-2008 Smart Framework team - Stepan Sindelar, Vojtech Vit
 * @license    http://www.opensource.org/licenses/bsd-license.php	New BSD License
 */

/**
 * 
 */
require_once 'Zend/Translate.php';

/**
 * Library class for creating translate instances.
 * See the comment of method createTranslate.
 *
 * @package SmartL_Zend
 * @subpackage Translate
 */
class SmartL_Zend_Translate {
	/**
	 * One adapter has only one instance.
	 * This array holds all adapters indexed by their name.
	 *
	 * @var array
	 */
	public static $_usedAdapters = array ();
	
	/**
	 * 2 dimensional array of files loaded per adapter.
	 *
	 * @var array[adapterName]=>array[filename]
	 */
	public static $_loadedFiles = array();
	
	private function __construct() {
	}
	
	/**
	 * This static method is in Smart Framework because:
	 * 
	 * 1) Zend Framework recommended to use only one instance of translate adapter in the same time(also because of cache), 
	 * but Smart Framework needs to create more Zend_Translate's instances in one time and this must be
	 * independent on which adapters are used. 
	 * This method is similar to singleton design pattern - we need only one instance of each adapter.
	 * 
	 * 2) It automaticly set the right locale according to SmartL_Application.
	 *
	 * @param string $adapter
	 * @param string $filename
	 * @param SmartL_Application Dependency injection, leave it null.
	 * @return Zend_Translate
	 */
	public static function createTranslate($adapter, $filename, SmartL_Application $application = null) 
	{
		if ($application === null) {
			$application = SmartL_Application::getInstance ();
		}
			
		//set up language
		$langs = $application->getLanguages ();
		$curLang = $langs [0];
		if (isset ( self::$_usedAdapters [$adapter] )) {
			// This adapter is somewhere used:

			/* avoid indexing into empty var */
			if ( empty(self::$_loadedFiles[$adapter]) ) {
				self::$_loadedFiles[$adapter] = array();
			}
			
			$result = self::$_usedAdapters [$adapter];
			if ( !isset(self::$_loadedFiles[$filename]) ) {									
				$result->addTranslation ( $filename, $curLang->getZendId (), array( 'disableNotices'=>true ) ); //just add translation
				self::$_loadedFiles[$filename] = true;
			}
		} else {			
			//create it
			$options = array( 'disableNotices'=>true );
			self::$_usedAdapters [$adapter] = $result = 
				new Zend_Translate ( $adapter, $filename, $curLang->getZendId (), $options );
			
			foreach ( $langs as $lang ) {
				if ( $result->isAvailable($lang->getZendId()) ) {
					$result->setLocale($lang->getZendId());
					break;	
				}				
			}
		}
		
		//return
		return $result;
	}
}